package com.intel.factorytest.activity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;

import com.intel.factorytest.R;

public class WLAN extends Activity{
    private static final String TEST_ITEM = "test_item";
          private static final String TEST_ITEM_RESULT = "test_item_result";
    private WifiManager mWifiManager = null; 
    private static final int SET_WIFI_STATUS = 1;
    private Timer mTimer;
    private IntentFilter mFilter = null;
        private Scanner mScanner;
        private BroadcastReceiver mReceiver;
    private TextView wifiText = null;
    private boolean is_pass;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == SET_WIFI_STATUS){
                
                mWifiManager.setWifiEnabled(true);
            }

        }
    }; 
    public void onCreate(Bundle b){
        super.onCreate(b);
        Intent intent = getIntent();
        String orientationStr = intent.getStringExtra("sd_orientation");
        int orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        Log.i("util","orientationStr = " + orientationStr);
        if(orientationStr.equals("SCREEN_ORIENTATION_PORTRAIT")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            super.setRequestedOrientation(orientation);

        } else if(orientationStr.equals("SCREEN_ORIENTATION_LANDSCAPE")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            super.setRequestedOrientation(orientation);

        }
        mFilter = new IntentFilter();
            mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                handleEvent(context, intent);
            }
        };

            mScanner = new Scanner();
        mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
        wifiText = new TextView(this);
        wifiText.setTextSize(24.0f);
        wifiText.setGravity(Gravity.CENTER);
        wifiText.setText(this.getString(R.string.SERVICEMENU_SEARCH_TXT));
        setContentView(wifiText);
        
    
     }

    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mFilter, "permission.CIT_ALLOW_BROADCAST", null);
        mTimer = new Timer();
        mTimer.schedule(new TimerTask(){
            @Override
            public void run() {
                mHandler.sendEmptyMessage(SET_WIFI_STATUS);
            }
    
        }, 1000);    


    }

    private void handleEvent(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i("meilianggang", "action = " + action);
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
                updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
            WifiManager.WIFI_STATE_UNKNOWN));
            Log.i("meilianggang", "updateWifiState");
        } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action)){
                List<ScanResult> results = mWifiManager.getScanResults();
            //results.size();
            String tmpStr = this.getString(R.string.SERVICEMENU_OPEN_TXT) + "\n" + this.getString(R.string.SERVICEMENU_SCAN_RESULT_TXT) + results.size();
            is_pass = false;
            if(results.size() > 0) {
                is_pass = true;
                tmpStr +=  "\n" + this.getString(R.string.SERVICEMENU_TEST_RESULT_TXT); 
            }
            wifiText.setText(tmpStr);
            Log.i("meilianggang", "results.size() = " + results.size());
        }
    }
    private void updateWifiState(int state) {
        switch (state) {
            case WifiManager.WIFI_STATE_ENABLED:
            wifiText.setText(this.getString(R.string.SERVICEMENU_OPEN_TXT));
            mScanner.resume();
            return; // not break, to avoid the call to pause() below

            case WifiManager.WIFI_STATE_ENABLING:
            break;

            case WifiManager.WIFI_STATE_DISABLED:
            is_pass = false;
            wifiText.setText(this.getString(R.string.SERVICEMENU_TEST_RESULT_FAIL_TXT));
            break;
        }

        mScanner.pause();
    }
    @Override
    public void onPause() {
        super.onPause();
        this.unregisterReceiver(mReceiver);
        mScanner.pause();
    }
    private class Scanner extends Handler {
        private int mRetry = 0;

        void resume() {
            if (!hasMessages(0)) {
            sendEmptyMessage(0);
            }
        }

        void forceScan() {
            removeMessages(0);
            sendEmptyMessage(0);
        }

        void pause() {
            mRetry = 0;
            removeMessages(0);
        }

        @Override
        public void handleMessage(Message message) {
            if (mWifiManager.startScan()) {
            mRetry = 0;
            } else if (++mRetry >= 3) {
            mRetry = 0;
            return;
            }
            sendEmptyMessageDelayed(0, 10 * 1000);
        }
    }


    private void setTestResult () {
        Intent intent = new Intent();
        Intent mIntent = getIntent();
        int pos = mIntent.getIntExtra(TEST_ITEM,-1);
        intent.putExtra(TEST_ITEM,pos);
        intent.putExtra(TEST_ITEM_RESULT,is_pass);
        setResult(0, intent);
    }
    @Override
    public void finish() {
        setTestResult (); 
        super.finish();
    }
}
    
